<?php
/**
 * @file 
 */
function nodejschat_settings($form, &$form_state = NULL) {
  static $themes;
  global $user, $language;
  $roles = user_roles();
  $admin_role_rid = variable_get('user_admin_role', FALSE);

  $settings = variable_get('nodejschat_default_settings', array());

  if ($admin_role_rid) {
    unset($roles[$admin_role_rid]);
  }

  $form['nodejschat_default_settings'] = array(
    '#type' => 'fieldset',
    '#title' => 'Configuration',
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#tree' => TRUE
  );
  $form['nodejschat_default_settings']['roles'] = array(
    '#type' => 'select',
    '#multiple' => TRUE,
    '#title' => t('Which roles have use access to this Public chat room'),
    '#options' => $roles,
    '#default_value' => $settings['roles'],
  );
  $form['nodejschat_default_settings']['anon_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name to be used with anonymous users'),
    '#description' => t("Please specify the name to be used with anonymous users. It shouldn't be long. Ideally it should be between 4 to 7 characters."),
    '#default_value' => $settings['anon_name'],
  );
  $form['nodejschat_default_settings']['replacement_patterns'] = array(
    '#type' => 'fieldset',
    '#title' => t('Replacement patterns'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    'anon_name_tokens' => array(
      '#theme' => 'token_tree',
      '#token_types' => array('global', 'nodejschat'),
      '#global_types' => TRUE,
      '#click_insert' => TRUE,
      '#group' => 'email',
    )
  );
  $form['nodejschat_default_settings']['ask_anon_email'] = array(
    '#type' => 'checkbox',
    '#title' => t('Ask anonymous email'),
    '#description' => t('Show/hide email field in the entry'),
    '#default_value' => $settings['ask_anon_email'],
  );
  $form['nodejschat_default_settings']['command_prefix'] = array(
    '#type' => 'textfield',
    '#title' => t('Command prefix'),
    '#description' => t('Prefix to be used with messages command.'),
    '#default_value' => $settings['command_prefix'],
  );
  $form['nodejschat_default_settings']['message_posted'] = array(
    '#type' => 'checkbox',
    '#title' => t('Display author and date information. '),
    '#description' => t('Author username and publish date will be displayed.'),
    '#default_value' => $settings['message_posted'],
  );
  $form['nodejschat_default_settings']['msg_date_format'] = array(
    '#type' => 'textfield',
    '#title' => t('Datetime format'),
    '#description' => t('Message datetime format.'),
    '#default_value' => $settings['msg_date_format'],
  );
  $form['nodejschat_default_settings']['user_picture'] = array(
    '#type' => 'checkbox',
    '#title' => t('User Pictures'),
    '#description' => t('Select whether to show user pictures in chat.'),
    '#default_value' => $settings['user_picture'],
  );
  // Get a list of all style names for our form options.
  $styles = array('' => t('None (original image)'));
  foreach (image_styles() as $id => $style) {
    $styles[$id] = $id;
  }
  $form['nodejschat_default_settings']['user_picture_style'] = array(
    '#type' => 'select',
    '#title' => t('User picture style'),
    '#options' => $styles,
    '#default_value' => $settings['user_picture_style'],
  );
  if ($formats = filter_formats($user)) {
    $format_options = array();
    foreach ($formats as $format) {
      $format_options[$format->format] = $format->name;
    }
    $form['nodejschat_default_settings']['msg_format'] = array(
      '#type' => 'select',
      '#title' => t('Message output format'),
      '#options' => $format_options,
      '#default_value' => $settings['msg_format'],
    );
  }

  $form['nodejschat_default_settings']['msg_amount'] = array(
    '#type' => 'textfield',
    '#title' => t('Message amount'),
    '#default_value' => $settings['msg_amount'],
  );

  $theme_options = array('' => t('--Choose theme--'));
  if (!isset($themes)) {
    $themes = nodejschat_load_themes();
    foreach ($themes as $name => $theme) {
      $theme_options[$name] = $theme['name'];
    }
  }

  $form['nodejschat_default_settings']['theme'] = array(
    '#type' => 'select',
    '#title' => t('Theme'),
    '#description' => t('All themes from inside the <em>themes</em> folder will be displayed here.'),
    '#options' => $theme_options,
    '#default_value' => $settings['theme'],
  );
  return system_settings_form($form);
}

/**
 * Page callback: Generates the appropriate nodejschat administration form.
 *
 * This function generates the nodejschat registration, multiple nodejschat cancellation,
 * or filtered nodejschat list admin form, depending on the argument and the POST
 * form values.
 *
 * @param string $callback_arg
 *   (optional) Indicates which form to build. Defaults to '', which will
 *   trigger the nodejschat filter form. If the POST value 'op' is present, this
 *   function uses that value as the callback argument.
 *
 * @return string
 *   A renderable form array for the respective request.
 */
function nodejschat_admin($callback_arg = '') {
  $op = isset($_POST['op']) ? $_POST['op'] : $callback_arg;

  switch ($op) {
    case t('Create new chat'):
    case 'create':
      $build['nodejschat_create'] = drupal_get_form('nodejschat_create');
      break;
    default:
      if (!empty($_POST['nodejschats']) && isset($_POST['operation']) && ($_POST['operation'] == 'delete')) {
        $build['nodejschat_multiple_delete_confirm'] = drupal_get_form('nodejschat_multiple_delete_confirm');
      }
      else {
        $build['nodejschat_filter_form'] = drupal_get_form('nodejschat_filter_form');
        $build['nodejschat_admin_nodejschat'] = drupal_get_form('nodejschat_admin_nodejschat');
      }
  }
  return $build;
}

/**
 * Form builder; Return form for user administration filters.
 *
 * @ingroup forms
 * @see nodejschat_filter_form_submit()
 */
function nodejschat_filter_form() {
  $session = isset($_SESSION['nodejschat_overview_filter']) ? $_SESSION['nodejschat_overview_filter'] : array();
  $i = 0;
  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only nodejschats where'),
    '#theme' => 'exposed_filters__nodejschat',
  );
  $form['filters']['status'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('clearfix')),
    '#prefix' => ($i ? '<div class="additional-filters">' . t('and where') . '</div>' : ''),
  );
  $form['filters']['status']['filters'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('filters')),
  );
  $options = array('' => t('Choose status')) + nodejschat_statuses();
  $form['filters']['status']['filters']['status'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('Status'),
    '#default_value' => isset($session['status']) ? $session['status'] : '',
  );

  $form['filters']['status']['actions'] = array(
    '#type' => 'actions',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form['filters']['status']['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => (count($session) ? t('Reset') : t('Filter')),
  );

  return $form;
}

/**
 * Process result from user administration filter form.
 */
function nodejschat_filter_form_submit($form, &$form_state) {
  $op = $form_state['values']['op'];
  switch ($op) {
    case t('Filter'):
      // Apply every filter that has a choice selected other than 'any'.
      if (isset($form_state['values']['status'])) {
        $_SESSION['nodejschat_overview_filter']['status'] = $form_state['values']['status'];
      }
      break;
    case t('Undo'):
      array_pop($_SESSION['nodejschat_overview_filter']);
      break;
    case t('Reset'):
      $_SESSION['nodejschat_overview_filter'] = array();
      break;
    case t('Update'):
      return;
  }

  $form_state['redirect'] = 'admin/nodejschat';
  return;
}

/**
 * Form builder; User administration page.
 *
 * @ingroup forms
 * @see nodejschat_admin_nodejschat_validate()
 * @see nodejschat_admin_nodejschat_submit()
 */
function nodejschat_admin_nodejschat() {

  $header = array(
    'title' => array('data' => t('Title'), 'field' => 'c.title'),
    'status' => array('data' => t('Status'), 'field' => 'c.status'),
    'public' => array('data' => t('Public')),
    'created' => array('data' => t('Created'), 'field' => 'c.created', 'sort' => 'desc'),
    'changed' => array('data' => t('Last access'), 'field' => 'c.changed'),
    'operations' => array('data' => t('Operations')),
  );

  $query = db_select('nodejschat', 'c');
  $query->condition('c.cid', 0, '<>');
  nodejschat_build_filter_query($query);

  $count_query = clone $query;
  $count_query->addExpression('COUNT(c.cid)');

  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query
    ->fields('c', array('cid', 'title', 'status', 'public', 'created', 'changed'))
    ->limit(50)
    ->orderByHeader($header)
    ->setCountQuery($count_query);
  $result = $query->execute();

  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#attributes' => array('class' => array('container-inline')),
  );
  $options = array();
  foreach (module_invoke_all('nodejschat_operations') as $operation => $array) {
    $options[$operation] = $array['label'];
  }
  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'unblock',
  );
  $options = array();
  $form['options']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
  );

  $destination = drupal_get_destination();

  $status = nodejschat_statuses();

  foreach ($result as $chat) {
    $options[$chat->cid] = array(
      'title' => l($chat->title, "nodejschat/$chat->cid", array('attributes' => array('target' => '_blank'))),
      'status' =>  $status[$chat->status],
      'public' => $chat->public ? t('Yes') : t('No'),
      'created' => date('d-m-Y H:i', $chat->created),
      'changed' =>  $chat->changed ? t('@time ago', array('@time' => format_interval(REQUEST_TIME - $chat->changed))) : t('never'),
      'operations' => array('data' => array('#type' => 'link', '#title' => t('edit'), '#href' => "nodejschat/$chat->cid/edit", '#options' => array('query' => $destination))),
    );
  }

  $form['nodejschats'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No people available.'),
  );
  $form['pager'] = array('#markup' => theme('pager'));

  return $form;
}

/**
 * Submit the user administration update form.
 */
function nodejschat_admin_nodejschat_submit($form, &$form_state) {
  $operations = module_invoke_all('nodejschat_operations', $form, $form_state);
  $operation = $operations[$form_state['values']['operation']];
  // Filter out unchecked accounts.
  $accounts = array_filter($form_state['values']['nodejschats']);
  if ($function = $operation['callback']) {
    // Add in callback arguments if present.
    if (isset($operation['callback arguments'])) {
      $args = array_merge(array($accounts), $operation['callback arguments']);
    }
    else {
      $args = array($accounts);
    }
    call_user_func_array($function, $args);

    drupal_set_message(t('The update has been performed.'));
  }
}

function nodejschat_admin_nodejschat_validate($form, &$form_state) {
  $form_state['values']['nodejschats'] = array_filter($form_state['values']['nodejschats']);
  if (count($form_state['values']['nodejschats']) == 0) {
    form_set_error('', t('No nodejschats selected.'));
  }
}

/**
 * Extends a query object for nodejschat administration filters based on session.
 *
 * @param $query
 *   Query object that should be filtered.
 */
function nodejschat_build_filter_query(SelectQuery $query) {
  // Extend Query with filter conditions.
  foreach (isset($_SESSION['nodejschat_overview_filter']) ? $_SESSION['nodejschat_overview_filter'] : array() as $key => $value) {
    $query->condition($key, $value);
  }
}

function nodejschat_multiple_delete_confirm($form, &$form_state) {
  $edit = $form_state['input'];

  $form['nodejschats'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  $nodejschats = nodejschat_load_multiple(array_keys(array_filter($edit['nodejschats'])));
  foreach ($nodejschats as $cid => $chat) {
    // Prevent user 1 from being canceled.
    if ($cid <= 1) {
      continue;
    }

    $form['nodejschats'][$cid] = array(
      '#type' => 'hidden',
      '#value' => $cid,
      '#prefix' => '<li>',
      '#suffix' => check_plain($chat->title) . "</li>\n",
    );
  }
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
  return confirm_form($form,
    t('Are you sure you want to cancel these nodejschats?'),
    'admin/nodejschat', t('This action cannot be undone.'),
    t('Delete nodejschats'), t('Cancel'));
}

/**
 * Submit handler for mass-account cancellation form.
 */
function nodejschat_multiple_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    foreach ($form_state['values']['nodejschats'] as $cid => $value) {
      nodejschat_delete_nodejschat($cid, 'nodejschat_delete_nodejschat');
    }
  }
  $form_state['redirect'] = 'admin/nodejschat';
}